<template>
    <div class="wb-container">
        <div class="page-header">当前位置：
            <span class="text-primary">{{ title }}</span>&nbsp;&nbsp;
            <span class="text-primary" v-if="title == '编辑'">修改<text class="text-info">【{{ editGoodsName }}】</text></span>
            <span class="text-primary" v-if="title == '编辑'">商户名称：<text class="text-info">【{{ userName }}】</text></span>
        </div>
        <div class="mian-content">
            <div class="jiben" v-if="isVision">
                <div class="btn">
                    <el-button style="background-color: #D4D7DE;" @click="goGoodsList"><el-icon>
                            <ArrowLeftBold />
                        </el-icon></el-button>
                    <el-button type="primary" @click="addVisionGoodsData">添加商品</el-button>
                </div>
                <div class="addGoodsTitle">
                    <div class="alert-box">
                        <div v-for="(item, index) in listAddFail" :key="index">
                            <div style="color: red;">{{ item }},商品列表已添加</div>
                        </div>
                    </div>
                    <div class="alert-box">
                        <div v-for="(it, index) in addSuccess" :key="index">
                            <div style="color: #509eff;">{{ it }},添加完成</div>
                        </div>
                    </div>
                </div>
                <el-table :data="list.goods" style="width: 100%;height: 600px;" size="small"
                    :header-cell-style="{ background: '#44abf7', color: '#fff', fontSize: '14px', height: '40px', letterSpacing: '2px' }">
                    <template #empty>
                        <el-empty description="暂无数据！" />
                    </template>
                    <el-table-column prop="admin_user_id" label="管理员ID" align="center" fixed />
                    <el-table-column prop="name" label="商品名称" align="center" />
                    <el-table-column prop="admin_user.account" label="商户名称" align="center" />
                    <el-table-column prop="image" label="图片" align="center">
                        <template #default="{ row }">
                            <el-image :src="row.image" style="width: 50px;height: 50px;margin: 10px;" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="unit" label="单位" align="center" />
                    <el-table-column prop="price" label="价格" align="center">
                        <template #default="{ row }">
                            <text v-show="!row.showmode">￥{{ row.price }}</text>
                            <el-input v-show="row.showmode" v-model="row.price" style="width:100px"></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作" min-width="200" align="center" fixed="right">
                        <template #default="scope2">
                            <div ref="refElement">
                                <span v-show="!scope2.row.showbtn">
                                    <el-button type="primary" @click="clickEdit(scope2)">修改</el-button>
                                </span>
                                <span v-show="scope2.row.showbtn">
                                    <el-button type="danger" @click="saveClick(scope2.row)">保存</el-button>
                                </span>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="addDeviceGoods-btn">
                    <el-button @click="removeDeviceGoods">取消</el-button>
                    <el-button type="primary" @click="addDeviceGoods">添加</el-button>
                </div>
            </div>
            <div class="jiben" v-else="!isVision">
                <div>
                    <el-button style="background-color: #D4D7DE;" @click="goGoodsList"><el-icon>
                            <ArrowLeftBold />
                        </el-icon></el-button>
                </div>
                <div class="content">
                    <div class="region-goods-details row">
                        <el-row>
                            <el-col :span="4">
                                <div class="region-goods-left">基本信息</div>
                            </el-col>
                            <el-col :span="20">
                                <div class="region-goods-right">
                                    <el-form :model="form" label-width="120px" ref="ruleFormRef">
                                        <el-form-item label="商品名称"
                                            :rules="{ required: true, message: '此项必须填写', trigger: 'blur' }">
                                            <el-input v-model="form.name" placeholder="输入商品名称" style="width: 700px;" />
                                        </el-form-item>
                                    </el-form>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                    <div class="region-goods-details">
                        <el-row>
                            <el-col :span="4">
                                <div class="region-goods-left ">商品信息</div>
                            </el-col>
                            <el-col :span="20">
                                <div class="region-goods-right ">
                                    <el-form :model="form" label-width="120px" ref="ruleFormRef">
                                        <el-form-item label="计费方式"
                                            :rules="{ required: true, message: '此项必须填写', trigger: 'blur' }">
                                            <el-radio-group v-model="form.sales_type">
                                                <el-radio label="1" size="large">计件</el-radio>
                                                <el-radio label="2" size="large">称重</el-radio>
                                            </el-radio-group>
                                        </el-form-item>
                                        <el-form-item label="商品分类">
                                            <el-select v-model="form.goods_cate_id" clearable placeholder="选择商品分类"
                                                @change="handelChangeSelect">
                                                <el-option v-for="item in list.cateList" :key="item.id" :label="item.name"
                                                    :value="item.id" />
                                            </el-select>
                                        </el-form-item>
                                        <el-form-item label="商品价格"
                                            :rules="{ required: true, message: '此项必须填写', trigger: 'blur' }">
                                            <div class="input-group">
                                                <el-input v-model="form.price" style="width:200px;height:30px" />
                                                <span>元 <i v-if="form.sales_type == '1'">单位</i></span>
                                                <el-input placeholder="单位，如：个/件/包" style="width:200px;height:30px"
                                                    v-model="form.unit" v-if="form.sales_type == '1'" />
                                                <span v-if="form.sales_type == '1'">原价</span>
                                                <el-input style=" width:200px;height:30px" v-model="form.cost_price"
                                                    v-if="form.sales_type == '1'" />
                                                <span v-if="form.sales_type == '1'">元</span>
                                            </div>
                                        </el-form-item>
                                        <el-form-item label="单价商品重量" class="weight_wave" v-if="form.sales_type == '1'"
                                            :rules="{ required: true, message: '此项必须填写', trigger: 'blur' }">
                                            <div class="input-weight">
                                                <el-input v-model="form.weight" />
                                                <span>克</span>
                                            </div>
                                            <span>计时或计件时，一件商品的重量，称重时，一份商品的重量</span>
                                        </el-form-item>
                                        <!-- 图片上传 -->
                                        <el-form-item label="商品图片"
                                            :rules="{ required: true, message: '此项必须填写', trigger: 'blur' }"
                                            style="align-items: flex-start;">
                                            <div class="input-img">
                                                <el-input type="text" placeholder="上传图片" v-model="form.image" disabled />
                                                <el-upload class="upload-demo" :show-file-list="false"
                                                    :on-change="uploadChange" :auto-upload="false"
                                                    :before-upload="beforeAvatarUpload" accept="image/gif, image/jpeg">
                                                    <el-button type="primary">上传图片</el-button>
                                                </el-upload>
                                            </div>
                                        </el-form-item>
                                        <el-form-item label="商品类型" v-if="form.sales_type == '1'"
                                            :rules="{ required: true, message: '此项必须填写', trigger: 'change' }">
                                            <el-radio-group v-model="form.type" class="ml-4">
                                                <el-radio label="1" size="large">称重商品</el-radio>
                                                <el-radio label="2" size="large">视觉商品</el-radio>
                                            </el-radio-group>
                                        </el-form-item>
                                        <el-form-item label="标签" v-if="isLable"
                                            :rules="{ required: true, message: '此项必须填写', trigger: 'blur' }">
                                            <el-input v-model="form.lable" placeholder="标签首字母大写" style="width: 700px;" />
                                        </el-form-item>
                                        <el-form-item label="重量波动值" v-if="form.sales_type == '1'">
                                            <div class="input-weight">
                                                <el-input v-model.number="form.weight_wave" />
                                                <span>克</span>
                                            </div>
                                            <span>预计重量波动范围(例如商品重量100g,波动范围10g,称重称出来90g或者110g也可购买)</span>
                                        </el-form-item>
                                        <el-form-item label="库存" v-if="form.sales_type == '1'">
                                            <el-input v-model.number="form.stock" style="width: 200px;"
                                                placeholder="输入商品库存" />
                                        </el-form-item>
                                        <el-form-item label="状态"
                                            :rules="{ required: true, message: '此项必须填写', trigger: 'blur' }">
                                            <el-radio-group v-model="form.status" class="ml-4">
                                                <el-radio label="1" size="large">上架</el-radio>
                                                <el-radio label="2" size="large">下架</el-radio>
                                            </el-radio-group>
                                        </el-form-item>
                                    </el-form>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                </div>
                <div class="form-group">
                    <el-row>
                        <el-col :span="4"></el-col>
                        <el-col :span="20">
                            <el-button @click="resetForm()">取消</el-button>
                            <el-button type="primary" @click="DetaliClick()">保存商品</el-button>
                        </el-col>
                    </el-row>
                </div>
            </div>
        </div>


        <el-dialog v-model="dialogVisionGoodsVisible" title="视觉商品">
            <div class="visionGoodsSearch">
                <el-input v-model="goodsName" placeholder="输入商品名称"></el-input>
                <el-button type="primary" @click="searchClick">搜索</el-button>
            </div>
            <el-table ref="refVisionGoods" :data="list.gridData" style="width: 100%;height:400px;"
                :header-cell-style="{ background: '#44abf7', color: '#fff' }" @select="clickSelect"
                @select-all="clickSelectAll" @selection-change="seleChange">
                <template #empty>
                    <el-empty description="暂无数据！" />
                </template>
                <el-table-column type="selection" align="center" width="50" />
                <el-table-column prop="admin_user_id" label="管理员ID" align="center" fixed />
                <el-table-column prop="name" label="商品名称" align="center" />
                <el-table-column prop="admin_user.account" label="商户名称" align="center" />
                <el-table-column prop="image" label="图片" align="center">
                    <template #default="{ row }">
                        <el-image :src="row.image" style="width: 50px;height: 50px;" />
                    </template>
                </el-table-column>
                <el-table-column prop="unit" label="单位" align="center" />
                <el-table-column prop="price" label="价格" align="center">
                    <template #default="{ row }">
                        <text style="color: #17d874">￥{{ row.price }}</text>
                    </template>
                </el-table-column>
            </el-table>
            <div class="demo-pagination-block">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[15, 20, 25, 30]" :small="small" :disabled="disabled" :background="background"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
            <div class="clickSelect-btn">
                <el-button @click="cancelClick()">取消</el-button>
                <el-button type="primary" @click="SelectProduct">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElRow, ElForm, ElMessage } from 'element-plus';
import { goodsAdd, goodsEdit, goodsList } from '@/api/goods'
import { goodsCateList } from '@/api/GoodsCate'
import { useRouter } from 'vue-router';
import { jsonFlatten } from '@/utlis/index'
import { uploadImg, developBaseUrl } from '@/api/public'
import store from '@/store';

const router = useRouter()
const title = ref('')
const userName = ref('')
const editGoodsName = ref('')
const refVisionGoods = ref()
const form = reactive({
    name: '',
    unit: '',
    goods_cate_id: '',
    image: '',
    price: 0,
    cost_price: 0,
    weight: 0,
    weight_wave: 0,
    stock: 0,
    status: '1',
    sales_type: "1",
    type: '1',
    // lable: ''
})
const list = reactive({
    name: '',
    cateList: [],
    goods: [],
    gridData: [],
    visionListChange: [],
    VisionGoodsData: [],
    selectChange: [],
    goodsObj: {
        limit: 15,
        page: 1,
        name: '',
        type: 2
    },
    cancelData: []
})
const isGoodsAdd = ref(false)
const refElement = ref()
const goodsName = ref('')
const listAddFail = ref([])
const addSuccess = ref([])
//第二个表单的值
const checked = ref(false)
const isLable = ref(false)
const isVision = ref(false)
const dialogVisionGoodsVisible = ref(false)
const tbsts = ref()
//分页
const currentPage = ref(1)
const pageSize = ref(15)
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
const total = ref(0)

//返回列表
const goGoodsList = () => {
    if (JSON.parse(userName.value).role_name.includes('BOSS') || JSON.parse(userName.value).role_name.includes('视觉商家')) {
        router.push('/commodity/myData')
    } else {
        router.push('/commodity/list')
    }
}
const getGoodsCate = async () => {
    const cate = await goodsCateList().then(s => {
        const { code, data } = s
        if (code == 200) {
            list.cateList = data.data
        }
    })
}
//获取视觉商品列表
const getVisionGoodsList = async () => {
    list.goodsObj.name = goodsName.value
    const visionList = await goodsList(list.goodsObj).then(res => {
        const { code, data } = res
        if (code == 200) {
            list.gridData = data.data
            total.value = data.total
        }
    })
}
//搜索视觉商品
const searchClick = () => {
    getVisionGoodsList()
}
watch(goodsName, (value) => {
    if (value === '') {
        getVisionGoodsList()
    }
})
const handelChangeSelect = (val) => {
    form.goods_cate_id = val
}
onMounted(() => {
    getGoodsCate()
    getVisionGoodsList()
    userName.value = store.state.UserInfo
    if (JSON.parse(userName.value).role_name.includes('BOSS')) {
        isLable.value = true
    }
    if (JSON.parse(userName.value).role_name.includes('视觉商家')) {
        isVision.value = true
    }
})

//表单编辑传过来的值
const historyParam = history.state.editList
if (historyParam) {
    form.name = historyParam.name
    form.unit = historyParam.unit
    form.goods_cate_id = historyParam.goods_cate_id
    form.image = historyParam.image
    form.price = historyParam.price
    form.cost_price = historyParam.cost_price
    form.weight = historyParam.weight
    form.weight_wave = historyParam.weight_wave
    form.stock = historyParam.stock
    form.status = String(historyParam.status)
    form.lable = historyParam.lable
    form.type = String(historyParam.type)
    form.ifEdit = 0
    title.value = '编辑商品'
    editGoodsName.value = historyParam.name
} else {
    title.value = '添加商品'
}
const DetaliClick = async () => {
    if (form.ifEdit === 0) {
        let id = historyParam.id
        let data = []
        for (let i in form) {
            let o = {};
            o[i] = form[i];
            data.push(o);
        }
        let newArr = data.filter(item => item.ifEdit !== 0);
        let array = { ...newArr }
        let dataEdit = jsonFlatten(array)
        const edit = await goodsEdit(id, dataEdit).then(r => {
            const { code, data } = r
            if (code == 200) {
                ElMessage.success('编辑成功')
            }
        })
    } else {
        const addData = await goodsAdd(form).then(res => {
            const { code, data } = res
            if (code === 200) {
                ElMessage.success('商品添加成功')
            }
        })
    }
}
const resetForm = () => {
    form.name = '',
        form.unit = '',
        form.goods_cate_id = '',
        form.image = '',
        form.price = '',
        form.cost_price = '',
        form.weight = '',
        form.weight_wave = '',
        form.stock = '',
        form.status = '1',
        form.sales_type = "1",
        form.type = '1',
        form.lable = ''
}
const beforeAvatarUpload = (file) => {
    //判断size
    if (file.type == 'image/jpg' || file.type == 'image/png') {
        const result = verificationPicSize(file, 200, 'K')
        if (!result) {
            ElMessage.error('jpg/png小于200k')
            return false
        } else {
            return true
        }
    } else if (file.type == 'image/gif') {
        const result = verificationPicSize(file, 2, 'M')
        if (!result) {
            ElMessage.error('gif小于2m')
            return false
        } else {
            return true
        }
    }
    const verificationPicSize = (
        file,
        limit,
        unit
    ) => {
        if (!file || !limit || !unit) return false

        if (unit == 'K') {
            if (file.size / 1024 > limit) {
                return false
            } else {
                return true
            }
        } else if (unit == 'M') {
            if (file.size / 1024 / 1024 > limit) {
                return false
            } else {
                return true
            }
        } else {
            return false
        }
    }
}
const dialogVisible = ref(false)
const uploadChange = async (file) => {
    if (!file) return
    var fileTypes = ['image/jpg', 'image/png', 'image/gif', "image/jpeg", "image/webp"] // 图片限制的格式类型
    if (!fileTypes.includes(file.raw.type)) {
        ElMessage.warning('当前图片仅支持格式为：' + fileTypes.join(' ，'))
        return false
    }
    let fd = new FormData()
    fd.append('image', file.raw)
    // console.log(fd.get('image', '上传图片的信息'));
    const img = await uploadImg(fd).then(p => {
        const { code, data } = p
        if (code == 200) {
            form.image = developBaseUrl + data.slice(7)
            ElMessage.success('图片上传成功')
        }
    })
    dialogVisible.value = true
}
const addVisionGoodsData = () => {
    dialogVisionGoodsVisible.value = true
}
const clickSelect = (selection, row) => {
    list.VisionGoodsData = selection
}
const clickSelectAll = (selection) => {
    list.VisionGoodsData = selection
}
const seleChange = (data) => {
    list.cancelData = data
}
const clickEdit = (scope1) => {
    tbsts.value = 'xg'
    btngroupChange(tbsts.value, scope1)
}
//表格按钮的变化
function btngroupChange(tbstsvalue, scope1) {
    // 1、表格处于非修改状态
    if (tbstsvalue == "xg") {
        // 使修改项显示为true（变为可修改状态）
        scope1.row.showmode = true
        // 使按钮组显示为 保存/取消 按钮
        scope1.row.showbtn = true
    } else if (tbstsvalue == "fxg") {
        // 使修改项显示为false（变为不可修改状态）
        scope1.row.showmode = false
        // 使按钮组显示为 编辑/取消 按钮
        scope1.row.showbtn = false
    }
}
//修改保存
const saveClick = async (row) => {
    row.showmode = false
    row.showbtn = false
}
const SelectProduct = () => {
    const result = Array.from(new Set(list.VisionGoodsData))
    list.goods = result
    dialogVisionGoodsVisible.value = false
}
const cancelClick = () => {
    dialogVisionGoodsVisible.value = false
    if (list.cancelData.length > 0) {
        refVisionGoods.value.clearSelection()
    }
    list.cancelData = []
}
const removeDeviceGoods = () => {
    if (list.goods.length > 0) {
        refVisionGoods.value.clearSelection()
    }
    list.goods = []
}
//绑定视觉设备商品
const addDeviceGoods = () => {
    addSuccess.value = []
    listAddFail.value = []
    refVisionGoods.value.clearSelection()
    for (let i = 0; i < list.goods.length; i++) {
        try {
            simulation(list.goods[i])
        } catch (err) {
            console.log(err);
        }
    }
}
const simulation = async (ele) => {
    let object = {}
    object.name = ele.name
    object.unit = ele.unit
    object.image = ele.image
    object.price = ele.price
    object.cost_price = ele.cost_price
    object.weight = ele.weight
    object.weight_wave = ele.weight_wave
    object.stock = ele.stock
    object.status = ele.status
    object.type = ele.type
    object.pid = ele.id
    await goodsAdd(object).then(res => {
        if (res == true) {
            addSuccess.value.push(ele.name)
        }
        if (res == 201) {
            listAddFail.value.push(ele.name)
        }
    })
}
//分页
const handleSizeChange = (val) => {
    list.goodsObj.limit = val
    getVisionGoodsList()

}
const handleCurrentChange = (value) => {
    list.goodsObj.page = value
    getVisionGoodsList()
}
</script>
<style lang="less" scoped>
.jiben {
    display: flex;
    flex-direction: column;
    width: 100%;
    padding: 10px 30px 20px 30px;
    background-color: #fff;
}

.btn {
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px solid #efefef;
    height: 45px;
}


.content {
    padding: 15px;
}

.region-goods-details {
    background: #f8f8f8;
    margin-bottom: 10px;
    padding: 0 10px;
}


.region-goods-left {
    text-align: center;
    font-weight: bold;
    color: #333;
    font-size: 14px;
    padding: 20px 0;
}

.region-goods-right {
    border-left: 3px solid #fff;
    padding: 10px 10px;
}

.form-group {
    margin-bottom: 15px;
}

.input-group {
    display: table;
    border-collapse: separate;

    span {
        background-color: #fff;
        border: 1px solid #efefef;
        border-radius: 1px;
        color: #999999;
        font-size: 12px;
        font-weight: 400;
        padding: 6px 12px;
        text-align: center;
    }
}

.input-weight {
    display: flex;

    span {
        background-color: #fff;
        border: 1px solid #efefef;
        border-radius: 1px;
        color: #999999;
        font-size: 12px;
        font-weight: 400;
        padding: 0 12px;
        text-align: center;
    }
}

.input-img {
    display: flex;
    width: 60%;
    height: 100%;
}

.help-block {
    display: block;
    color: #999;
    font-size: 12px;
}

.text-info {
    color: #3abbdb !important;
}

.el-form-item {
    align-items: center;
}

:deep(.el-dialog) {
    header {
        background: rgb(68, 171, 247);
        margin-right: 0;

        .el-dialog__title {
            color: #fff;
        }

        .el-dialog__headerbtn i {
            color: #fff;
        }
    }
}

:deep(.el-dialog__close) {
    color: #fff;
}

:deep(.el-button) {
    letter-spacing: 2px;
}

.clickSelect-btn {
    margin-top: 50px;
    display: flex;
    justify-content: flex-end;
    padding-right: 50px;
}

.addDeviceGoods-btn {
    display: flex;
    justify-content: flex-end;
    margin-right: 100px;
    margin: 20px 100px 0 0;
}

.visionGoodsSearch {
    display: flex;
    justify-content: flex-end;

    .el-input {
        width: 200px;
        margin-bottom: 20px;
    }
}

.fail {
    color: #409eff;
}

.addGoodsTitle {
    width: 700px;
    display: flex;
    margin-bottom: 10px;

    .alert-box {
        display: flex;
        flex-direction: column;
        margin-right: 20px;
    }
}
</style>